package com.example.wechat114.service.impl;

import com.example.wechat114.commons.Constant;
import com.example.wechat114.commons.JsonBean;
import com.example.wechat114.entity.WxUser;
import com.example.wechat114.mapper.WxUserMapper;
import com.example.wechat114.service.WechatService;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author CHENCHEN
 * @create 2021-03-29 14:45
 */
@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    private WxUserMapper wxUserMapper;

    /** Logger实例 */
    static final Logger logger = LoggerFactory.getLogger(WechatService.class);

    @Override
    public String handleWxMsg(Map<String, String> map) {
        String resultXml = "";
        String toUserName = map.get("ToUserName");//开发者微信号
        String fromUserName = map.get("FromUserName");//发送方帐号（一个OpenID）
        String createTime = map.get("CreateTime");//消息创建时间 （整型）
        String msgType = map.get("MsgType");//消息类型，event
        //事件类型方法
        if(msgType.equals("event")){
            resultXml = hanleEvent(map.get("Event"), toUserName, fromUserName);
            logger.debug(resultXml);
        }
        return resultXml;
    }

    @Override
    public JsonBean oAuth(String code) {
        JsonBean jsonBean = new JsonBean(-1, "", null);
        if(code != null){
            JSONObject jsonObject = Constant.getAccessTokenByCode(code);
            jsonBean = new JsonBean(0, "", jsonObject.get("openid").toString());
        }
        return jsonBean;
    }

    @Override
    public JsonBean jsConfig(String url) {
        JsonBean jsonBean = new JsonBean(-1, "", null);
        if(url != null){
            Map<String, String> map = Constant.getSignature(url);
            jsonBean = new JsonBean(0, "", map);
        }
        return jsonBean;
    }

    /**
     * 处理关注事件
     * @param event
     * @param openid
     * @return
     */
    private String hanleEvent(String event, String developerID, String openid){
        WxUser dbWxUser = wxUserMapper.selectByOpenid(openid);
        //事件类型，subscribe(订阅)、unsubscribe(取消订阅)
        if(event.equals("subscribe")){
            WxUser wxGetUserInfo = Constant.getWxUserInfoByUnionID(openid);
            if(dbWxUser == null){
                wxUserMapper.insert(wxGetUserInfo);
            }else{
                wxUserMapper.updateByPrimaryKeyOpenid(wxGetUserInfo);
            }
            return subscribeResultXml(developerID, openid);
        }else if(event.equals("unsubscribe")){
            dbWxUser.setSubscribe(0);
            wxUserMapper.updateByPrimaryKeyOpenid(dbWxUser);
        }
        return "";
    }

    /**
     * 返回关注后文本推送
     * @param developerID
     * @param openid
     * @return
     */
    private String subscribeResultXml(String developerID, String openid){
        String content = "轻松就医，3步挂号！\n" +
                "第一步：【<a href=\""+Constant.oAuth(Constant.URL + "/114/index.html", Constant.SNSAPI_USERINFO)+"\">注册账号+实名认证</a>】\n" +
                "第二步：【<a href=\""+Constant.oAuth(Constant.URL + "/114/center.html", Constant.SNSAPI_USERINFO)+"\">个人中心</a>】添加就诊人\n" +
                "第三步：【<a href=\""+Constant.oAuth(Constant.URL + "/114/index.html", Constant.SNSAPI_USERINFO)+"\">预约挂号</a>】\n" +
                "点击【<a href=\"https://w.url.cn/s/AaOzWFg\">挂号秘籍</a>】查看挂号方法\n" +
                "点击【<a href=\""+Constant.oAuth(Constant.URL + "/114/index.html", Constant.SNSAPI_USERINFO)+"\">按医院</a>】或【<a href=\""+Constant.oAuth(Constant.URL + "/114/all.html", Constant.SNSAPI_USERINFO)+"\">按科室</a>】挂号更便捷\n" +
                "点击【<a href=\""+Constant.oAuth(Constant.URL + "/114/center.html", Constant.SNSAPI_USERINFO)+"\">个人中心</a>】，可添加/修改就诊人信息、查看/取消订单\n" +
                "点击【申诉】提交问题，5个工作日内回复\n" +
                "点击【<a href=\""+Constant.oAuth(Constant.URL + "/114/help.html", Constant.SNSAPI_USERINFO)+"\">帮助中心</a>】解决注册、挂号、取消等问题";
        return "<xml>\n" +
                "  <ToUserName><![CDATA["+openid+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+developerID+"]]></FromUserName>\n" +
                "  <CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+content+"]]></Content>\n" +
                "</xml>";
    }
}
